<template>
  <a-modal
    :title="title"
    :width="width"
    :visible="visible"
    on-ok="handleOk"
    switch-fullscreen
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <a-menu
      style="width: 100%"
      :default-selected-keys="defaultSelectedKeys"
      mode="vertical"
      @click="handleClick"
    >
      <template v-for="item in collectionList">
        <a-menu-item
          :key="item.id"
        >
          {{ item.name }}
        </a-menu-item>
      </template>

    </a-menu>

    <a-input-search
      v-model="collectionName"
      style="margin-top: 50px"
      prefix="+"
      placeholder="新建收藏夹"
      enter-button="新建"
      @search="addCollection"
    />
  </a-modal>
</template>

<script>
import { getAction, postAction } from '@/api/manage'

export default {
  name: 'CollectionModal',
  data() {
    return {
      title: '登录',
      width: 600,
      visible: false,
      collectionList: [],
      defaultSelectedKeys: [],
      url: {
        initList: '/articleFavorites/getByUser',
        add: '/articleFavoritesSub/add',
        addCollection: '/articleFavorites/add'
      },
      articleId: '',
      collectionName: ''
    }
  },
  methods: {
    click(articleId) {
      this.articleId = articleId
      // 加在当前登陆人收藏夹
      getAction(this.url.initList, {}).then(res => {
        if (res.success) {
          this.collectionList = res.result
          if (res.result) {
            this.defaultSelectedKeys.push(res.result[0].id)
          }
        }
      })
      this.visible = true
    },
    handleCancel() {
      this.visible = false
    },
    handleOk() {
      const params = {
        'mainId': this.defaultSelectedKeys[0],
        'articleId': this.articleId
      }
      postAction(this.url.add, params).then(res => {
        if (res.success) {
          this.$emit('okCollection', res)
        }
      })
    },
    handleClick(e) {
      this.defaultSelectedKeys = []
      this.defaultSelectedKeys.push(e.key)
    },
    addCollection() {
      const formData = {
        name: this.collectionName
      }
      postAction(this.url.addCollection, formData).then((res) => {
        if (res.success) {
          this.collectionName = ''
          this.$message.success(res.message)
          this.defaultSelectedKeys = []
          this.click(this.articleId)
        } else {
          this.$message.warning(res.message)
        }
      }).finally(() => {
        this.confirmLoading = false
      })
    }
  }
}
</script>

<style scoped>

</style>
